package com.edu.learning.concurrent.sample.mode1;

import java.util.concurrent.*;

/**
 * @author ll
 * @Date 2017/10/23 16:50
 */
public class ProducerConsumerTest {
    private static final String FINISHED = "EOF";
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>(100);

        ExecutorService executorService = new ThreadPoolExecutor(
                32,
                32,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024),
                new ThreadPoolExecutor.AbortPolicy());

        executorService.execute(new Producer(blockingQueue));
        executorService.execute(new Consumer(blockingQueue));
        executorService.shutdown();
    }

    static class Producer implements Runnable {
        private BlockingQueue<String> blockingQueue;

        public Producer(BlockingQueue<String> blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            try {
                blockingQueue.put("Hello, test");
                blockingQueue.put(FINISHED);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Consumer implements Runnable {
        private BlockingQueue<String> blockingQueue;

        public Consumer(BlockingQueue<String> blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    System.out.println("Consumer输出 : " + blockingQueue.take());
                    if (FINISHED.equalsIgnoreCase(blockingQueue.take())) {
                        break;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
